package com.android.clinic.app.ui.doctor;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.clinic.app.ClinicApplication;
import com.android.clinic.app.R;
import com.android.clinic.app.base.BaseActivity;
import com.android.clinic.app.entity.DoctorReplyInfo;
import com.android.clinic.app.glide.ImageLoaderUtils;
import com.android.clinic.app.http.HttpClient;
import com.android.clinic.app.http.base.BaseObserver;
import com.android.clinic.app.http.utils.RxObservableUtils;
import com.android.clinic.app.utils.DisplayUtil;
import com.android.clinic.app.utils.TimeUtils;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.gyf.barlibrary.ImmersionBar;
import com.kennyc.view.MultiStateView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by cheng on 2018/3/27.
 * 名医咨询
 */
public class DoctorAdvisoryActivity extends BaseActivity implements OnRefreshListener {

    private SwipeToLoadLayout swipeToLoadLayout;
    private ListView listView;
    protected int pageNum = 1; // 当前页数

    private DoctorAdvisoryAdapter doctorAdapter;
    private List<DoctorReplyInfo> doctorTempList = new ArrayList<>();

    private Timer timer;
    private TimerTask task;

    private EditText etContent;
    private String inquireId = "";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_chat_listview;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ImmersionBar.with(this).keyboardEnable(true).init();
        setTitleBarTitle("咨询");
        setTitleBarLeftResource(R.drawable.icon_back);

        swipeToLoadLayout = (SwipeToLoadLayout) findViewById(R.id.swipeToLoadLayout);
        listView = (ListView) findViewById(R.id.swipe_target);
        swipeToLoadLayout.setOnRefreshListener(this);

        etContent = (EditText) this.findViewById(R.id.et_content);
        inquireId = this.getIntent().getStringExtra("inquireId");

        doctorAdapter = new DoctorAdvisoryAdapter();
        listView.setAdapter(doctorAdapter);
    }

    @Override
    protected void loadData() {
        super.loadData();
        getListReply();
    }

    /**
     * 获取医生回复列表
     */
    private void getListReply() {
        HttpClient.getHttpService().getAnswerRest(inquireId, 100, pageNum)
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        refreshComplete();
                        doctorTempList.clear();
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            List<DoctorReplyInfo> doctorReplyInfoList = JSON.parseArray(jsonObject.optJSONArray("result").toString(),
                                    DoctorReplyInfo.class);
                            int replySize = doctorReplyInfoList.size();
                            if (replySize > 0) {
                                setMultiStateView(MultiStateView.VIEW_STATE_CONTENT);
                                Collections.reverse(doctorReplyInfoList);
                                doctorTempList.addAll(doctorReplyInfoList);
                                doctorAdapter.setDoctorReplyList(doctorTempList);
                                listView.setSelection(doctorReplyInfoList.size());
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(String message) {
                        refreshComplete();
                        showToast(message);
                    }
                });
    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        new Handler().postDelayed(this::getListReply, 500);
    }

    private void refreshComplete() {
        if (swipeToLoadLayout.isRefreshing()) {
            swipeToLoadLayout.setRefreshing(false);
        }
    }

    private class DoctorAdvisoryAdapter extends BaseAdapter {

        private final static int USER = 0x01;    // 用户
        private final static int DOCTOR = 0x02;  // 医生

        private List<DoctorReplyInfo> doctorReplyList = new ArrayList<>();

        public void setDoctorReplyList(List<DoctorReplyInfo> doctorReplyList) {
            this.doctorReplyList = doctorReplyList;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return doctorReplyList.size();
        }

        @Override
        public int getItemViewType(int position) {
            if (doctorReplyList.get(position).getTypeNum().equals("1")) {
                return USER;
            } else {
                return DOCTOR;
            }
        }

        @Override
        public DoctorReplyInfo getItem(int position) {
            return doctorReplyList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (getItemViewType(position) == USER) {
                UserViewHolder userHolder;
                if (null == convertView || null == convertView.getTag(R.id.tag_user)) {
                    convertView = LayoutInflater.from(DoctorAdvisoryActivity.this).inflate(R.layout.item_chat_send_layout, null);
                    userHolder = new UserViewHolder();
                    userHolder.ivReplyHead = (ImageView) convertView.findViewById(R.id.iv_send_head);
                    userHolder.tvReplyText = (TextView) convertView.findViewById(R.id.tv_send);
                    userHolder.tvReplyTime = (TextView) convertView.findViewById(R.id.tv_send_time);
                    userHolder.tvReplyName = (TextView) convertView.findViewById(R.id.tv_send_name);
                    convertView.setTag(R.id.tag_user, userHolder);
                } else {
                    userHolder = (UserViewHolder) convertView.getTag(R.id.tag_user);
                }
                ImageLoaderUtils.getInstance().loadHeadImage(ClinicApplication.getUserInfo().getImgUrl(), userHolder.ivReplyHead,
                        DisplayUtil.dip2px(45), DisplayUtil.dip2px(45));
                userHolder.tvReplyText.setText(getItem(position).getContext());
                userHolder.tvReplyTime.setText(TimeUtils.getChatFormatTime(getItem(position).getCreateTime()));
                userHolder.tvReplyName.setText(getItem(position).getName());

            } else {
                DoctorViewHolder doctorHolder;
                if (null == convertView || null == convertView.getTag(R.id.tag_doctor)) {
                    convertView = LayoutInflater.from(DoctorAdvisoryActivity.this).inflate(R.layout.item_chat_from_layout, null);
                    doctorHolder = new DoctorViewHolder();
                    doctorHolder.ivReceiveHead = (ImageView) convertView.findViewById(R.id.iv_from_head);
                    doctorHolder.tvReceiveText = (TextView) convertView.findViewById(R.id.tv_from);
                    doctorHolder.tvReceiveTime = (TextView) convertView.findViewById(R.id.tv_from_time);
                    doctorHolder.tvReceiveName = (TextView) convertView.findViewById(R.id.tv_from_name);
                    convertView.setTag(R.id.tag_doctor, doctorHolder);
                } else {
                    doctorHolder = (DoctorViewHolder) convertView.getTag(R.id.tag_doctor);
                }
                ImageLoaderUtils.getInstance().loadHeadImage(getItem(position).getDoctorImgUrl(),
                        doctorHolder.ivReceiveHead, DisplayUtil.dip2px(45), DisplayUtil.dip2px(45));
                doctorHolder.tvReceiveText.setText(getItem(position).getContext());
                doctorHolder.tvReceiveTime.setText(TimeUtils.getChatFormatTime(getItem(position).getCreateTime()));
                doctorHolder.tvReceiveName.setText(getItem(position).getName());

            }
            return convertView;
        }

        class UserViewHolder {
            ImageView ivReplyHead;
            TextView tvReplyText, tvReplyTime, tvReplyName;
        }

        class DoctorViewHolder {
            ImageView ivReceiveHead;
            TextView tvReceiveText, tvReceiveTime, tvReceiveName;
        }
    }

    @Override
    protected void widgetClick(View v) {
        super.widgetClick(v);
        if (v.getId() == R.id.btn_send) {
            if (etContent.getText().length() == 0) {
                showToast("发送内容不能为空!");
                return;
            }
            sendReplyMessage(etContent.getText().toString().trim());
        }
    }

    /**
     * 添加本地临时数据
     * @param message
     */
    private void addTempReplyList(String message) {
        DoctorReplyInfo replyInfo = new DoctorReplyInfo();
        replyInfo.setUserId(ClinicApplication.getUserInfo().getId());
        replyInfo.setType("用户");
        replyInfo.setTypeNum("1");
        replyInfo.setContext(message);
        replyInfo.setCreateTime(System.currentTimeMillis());
        doctorTempList.add(replyInfo);
        doctorAdapter.setDoctorReplyList(doctorTempList);
        listView.setSelection(doctorTempList.size());
    }

    /**
     * 发送回复给医生
     * @param message
     */
    private void sendReplyMessage(String message) {
        HttpClient.getHttpService().sendReplyMessage(ClinicApplication.getUserInfo().getId(),
                inquireId, message)
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        addTempReplyList(message);
                        etContent.setText("");
                        hideKeyboard();
                        if (null == timer) {
                            timer = new Timer();
                            task = new TimerTask() {
                                @Override
                                public void run() {
                                    getListReply();
                                }
                            };
                            timer.schedule(task, 5000, 5000);
                        }
                    }

                    @Override
                    public void onFailure(String message) {

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null || task != null) {
            timer.cancel();
            task.cancel();
        }
    }

}
